package com.uhylab.uhuvinetest.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.uhylab.uhuvinetest.R;
import com.uhylab.uhuvinetest.base.UHBase;
import com.uhylab.uhuvinetest.base.UHBaseActivity;
import com.uhylab.uhuvinetest.bean.StringData;
import com.uhylab.uhuvinetest.bean.WoBean;
import com.uhylab.uhuvinetest.utils.VolleySingleton;
import com.uhylab.uhuvinetest.utils.sharedpreutils.SharedPreUtils;
import com.uhylab.uhuvinetest.utils.toastutil.ToastUtil;
import com.zhy.autolayout.AutoRelativeLayout;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

public class RegisteredWoActivity extends UHBaseActivity implements View.OnClickListener {

    private ImageView register_back;
    private EditText user_telphone;
    private AutoRelativeLayout loggon;
    private WoBean bean;
    private VolleySingleton volleySingleton;
    private ProgressDialog progressDialog;

    @Override
    public int bindLayout() {
        return R.layout.activity_registered_wo;
    }

    @Override
    public void initView(View view) {
        volleySingleton = VolleySingleton.getVolleySingleton(getApplicationContext());
        register_back = (ImageView) findViewById(R.id.register_back);
        user_telphone = (EditText) findViewById(R.id.user_telphone);
        loggon = (AutoRelativeLayout) findViewById(R.id.loggon);
        progressDialog = new ProgressDialog(this);
    }

    @Override
    public void doBusiness(Context mContext) {
        register_back.setOnClickListener(this);
        loggon.setOnClickListener(this);
    }


    private void isregest() {
        volleySingleton.removeRequest("isregest");
        //在这里设置需要post的json格式的数据
        Map<String, String> params = new HashMap<String, String>();
        params.put("phone", user_telphone.getText().toString());
        params.put("password", user_telphone.getText().toString());
        params.put("vercode", user_telphone.getText().toString());
        params.put("isthird", user_telphone.getText().toString());
        JSONObject jsonObject = new JSONObject(params);


        JsonObjectRequest jsonRegest = new JsonObjectRequest(Request.Method.POST, UHBase.newRegisteredUrl, jsonObject, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    Log.e("UHHomeFragment", response.toString());
                    logon();
                } catch (Exception e) {
                    Log.e("UHHomeFragment", e.toString());
                    Toast.makeText(RegisteredWoActivity.this, "获取失败请重试", Toast.LENGTH_SHORT).show();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("UHHomeFragment", "error:" + error);
            }
        }) {
//            @Override
//            protected Map<String, String> getParams() throws AuthFailureError {
//                //在这里设置需要post的参数
//                Map<String, String> params = new HashMap<String, String>();
//                params.put("phone", user_telphone.getText().toString());
//                params.put("password", user_telphone.getText().toString());
//                params.put("vercode", user_telphone.getText().toString());
//                params.put("isthird", user_telphone.getText().toString());
//                return params;
//            }


            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();
                headers.put("Accept", "application/json");
                headers.put("Content-Type", "application/json; charset=UTF-8");

                return headers;
            }


        };
        volleySingleton.addQueue(jsonRegest, "isregest");
    }


//    private void retrievePass() {
//        //在这里设置需要post的json格式的数据
//        Map<String, String> params = new HashMap<String, String>();
//        params.put("phone", user_telphone.getText().toString());
//        params.put("password", user_telphone.getText().toString());
//        params.put("vercode", user_telphone.getText().toString());
//        params.put("isthird", user_telphone.getText().toString());
//        JSONObject jsonObject = new JSONObject(params);
//
//
//        JsonObjectRequest retrievePass = new JsonObjectRequest(Request.Method.POST, UHBase.newRegisteredUrl, jsonObject, new Response.Listener<JSONObject>() {
//            @Override
//            public void onResponse(JSONObject response) {
//                Log.e("UHHomeFragment", response.toString());
//                try {
//                    Gson gson = new Gson();
//                    StringData dataee = gson.fromJson(response.toString(), StringData.class);
//                    if (dataee.getCode() == "0000") {
//                        //  Toast.makeText(RegisteredWoActivity.this, dataee.getMessage(), Toast.LENGTH_SHORT).show();
//                        logon();
//                    } else {
//
//                    }
//                } catch (Exception e) {
//                    Log.e("UHRegisteredActivity", "接口出错");
//                }
//
//            }
//        }, new Response.ErrorListener() {
//            @Override
//            public void onErrorResponse(VolleyError error) {
//                Log.e("UHHomeFragment", "retrievePass + error:" + error);
//            }
//        }) {
//
//            @Override
//            public Map<String, String> getHeaders() throws AuthFailureError {
//                HashMap<String, String> headers = new HashMap<String, String>();
//                headers.put("Accept", "application/json");
//                headers.put("Content-Type", "application/json; charset=UTF-8");
//
//                return headers;
//            }
////            @Override
////            protected Map<String, String> getParams() throws AuthFailureError {
////                //在这里设置需要post的参数
////                Map<String, String> params = new HashMap<String, String>();
////                params.put("telephone", user_telphone.getText().toString());
////                params.put("password", "123456");
////                return params;
////            }
//        };
//        volleySingleton.addQueue(retrievePass, "Request");
//    }


    private void logon() {
        StringRequest stringRequest = new StringRequest(Request.Method.GET, UHBase.newLogin + "phone=" + user_telphone.getText().toString() + "&password=" + user_telphone.getText().toString(), new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    Log.e("RegisteredWoActivity", response);
                    Gson gson = new Gson();
                    StringData dataee = gson.fromJson(response, StringData.class);
                    if (dataee.getCode().equals("0000")) {
                        dialog_dismiss();
                        Toast.makeText(RegisteredWoActivity.this, dataee.getMsg(), Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(RegisteredWoActivity.this, UHMainActivity.class);
                        startActivity(intent);
                        SharedPreUtils.setBoolean(getContext(), "is_Login", true);
                        SharedPreUtils.setString(getContext(), "user_tel", user_telphone.getText().toString());
                        SharedPreUtils.setString(getContext(), "user_password", user_telphone.getText().toString());
                        SharedPreUtils.setString(getContext(), "user_token", dataee.getData());
                        RegisteredWoActivity.this.finish();
                    } else if (dataee.getCode() == "0105") {
                        Toast.makeText(RegisteredWoActivity.this, dataee.getMsg(), Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    Toast.makeText(RegisteredWoActivity.this, "登陆失败请稍后再试", Toast.LENGTH_SHORT).show();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("UHHomeFragment", "error:" + error);
            }
        }) {
//            @Override
//            protected Map<String, String> getParams() throws AuthFailureError {
//                //在这里设置需要post的参数
//                Map<String, String> params = new HashMap<String, String>();
//                params.put("telephone", user_telphone.getText().toString());
//                params.put("password", "123456");
//                return params;
//            }
        };
        volleySingleton.addQueue(stringRequest, "logon");
    }

    private void dialog_dismiss() {
        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }


    @Override
    public void resume() {

    }

    @Override
    protected void onPause() {
        super.onPause();

    }

    @Override
    public void destroy() {
        volleySingleton.removeRequest("isregest");
        volleySingleton.removeRequest("Request");
        volleySingleton.removeRequest("logon");

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.register_back:
                // 返回上一页
                if (RegisteredWoActivity.this != null) {
                    finish();
                }
                break;
            case R.id.loggon:
                String telphone = user_telphone.getText().toString();
                int length = telphone.length();
                if (length == 0) {
                    ToastUtil.show(this, "请输入手机号！");
                } else if (length != 11) {
                    ToastUtil.show(this, "请输入正确的手机号");
                } else if (length == 11) {
                    String cu = "^((13[0-2])|(145)|(15[5-6])|(186)|(185)|(176)|(177))\\d{8}$";
                    if (telphone.matches(cu)) {
                        progressDialog.setMessage("正在登陆请稍后");
                        progressDialog.show();
                        //进行沃互联请求
                        long time = System.currentTimeMillis();
                        String url = "https://123.125.219.144:8443/mobileConnect/MobileConnect/authLogin.action?systemid=100009&mobile=" + telphone + "&pipe=2&reqtime=" + time + "&ispin=2";
                        OkHttpUtils
                                .get()//
                                .url(url)//
                                .build()//
                                .connTimeOut(1000000)
                                .readTimeOut(1000000)
                                .writeTimeOut(1000000)
                                .execute(new MyStringCallback());

                    } else {
                        ToastUtil.show(this, "该手机号不是联通手机号");
                    }
                }


                break;
            default:
                break;
        }
    }

    public class MyStringCallback extends StringCallback {

        @Override
        public void onResponse(String response, int id) {
            Log.e("TAG", "成功" + response);

            bean = new Gson().fromJson(response, WoBean.class);

            switch (bean.getResults().getStatus()) {
                case "00":
                    ToastUtil.show(RegisteredWoActivity.this, "登录成功");
                    isregest();

                    break;
                case "01":
                    ToastUtil.show(RegisteredWoActivity.this, "检验失败");
                    dialog_dismiss();
                    break;
                case "02":
                    ToastUtil.show(RegisteredWoActivity.this, "PIN码超时");
                    dialog_dismiss();
                    break;
                case "03":
                    ToastUtil.show(RegisteredWoActivity.this, "认证超时");
                    dialog_dismiss();
                    break;
                case "04":
                    ToastUtil.show(RegisteredWoActivity.this, "手机号码不存在");
                    dialog_dismiss();
                    break;
                case "05":
                    ToastUtil.show(RegisteredWoActivity.this, "参数错误");
                    dialog_dismiss();
                    break;
                case "06":
                    ToastUtil.show(RegisteredWoActivity.this, "请求超时");
                    dialog_dismiss();
                    break;
                case "07":
                    ToastUtil.show(RegisteredWoActivity.this, "手机号码已注销");
                    dialog_dismiss();
                    break;
                case "08":
                    ToastUtil.show(RegisteredWoActivity.this, "手机号码未开通");
                    dialog_dismiss();
                    break;
                case "09":
                    ToastUtil.show(RegisteredWoActivity.this, "系统标识不存在");
                    dialog_dismiss();
                    break;
                case "10":
                    ToastUtil.show(RegisteredWoActivity.this, "认证请求不存在");
                    dialog_dismiss();
                    break;
                case "11":
                    ToastUtil.show(RegisteredWoActivity.this, "用户取消登录");
                    dialog_dismiss();
                    break;


            }

        }


        @Override
        public void onError(Call call, Exception e, int id) {
            Log.d("MyStringCallback", "失败" + e.getMessage() + e.toString());

        }


    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            OkHttpUtils.delete();
            finish();
        }
        return false;
    }
}
